package mysql

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/model"
	"gorm.io/gorm"
)

type OrderJobDao interface {
	Create(ctx context.Context, orderJob *model.OrderJob) error
	FindByID(ctx context.Context, jobId int64) (*model.OrderJob, error)
	FindByOrderID(ctx context.Context, OrderID int64) (*model.OrderJob, error)
	FindByJobID(ctx context.Context, JobID int64) (*model.OrderJob, error)
}

func NewOrderJobDao(
	r *MysqlClient,
) OrderJobDao {
	return &orderJobDao{
		MysqlClient: r,
	}
}

type orderJobDao struct {
	*MysqlClient
}

func (r *orderJobDao) Create(ctx context.Context, orderJob *model.OrderJob) error {
	if err := r.DB(ctx).Create(orderJob).Error; err != nil {
		r.logger.WithContext(ctx).Error("orderJobDao|Create", zap.Error(err))
		return err
	}
	return nil
}

func (r *orderJobDao) FindByID(ctx context.Context, jobId int64) (*model.OrderJob, error) {
	orderJob := &model.OrderJob{}
	if err := r.DB(ctx).Where("id = ?", jobId).First(orderJob).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("orderJobDao|GetByID", zap.Error(err))
		return nil, err
	}
	return orderJob, nil
}

func (r *orderJobDao) FindByOrderID(ctx context.Context, OrderID int64) (*model.OrderJob, error) {
	orderJob := &model.OrderJob{}
	if err := r.DB(ctx).Where("order_id = ?", OrderID).First(orderJob).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("orderJobDao|FindByOrderID", zap.Error(err))
		return nil, err
	}
	return orderJob, nil
}

func (r *orderJobDao) FindByJobID(ctx context.Context, JobID int64) (*model.OrderJob, error) {
	orderJob := &model.OrderJob{}
	if err := r.DB(ctx).Where("job_id = ?", JobID).First(orderJob).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("orderJobDao|FindByJobID", zap.Error(err))
		return nil, err
	}
	return orderJob, nil
}